<template>
  <div class="flex">
    <div class="tableManage w-100%">
      <!-- <ContentWrap> -->
        <!-- 搜索区域 -->
        <div class="search-form">
          <Search
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
        </div>

        <ElDivider />

        <!-- 操作按钮区域 -->
        <div class="mb-10px" >
          <BaseButton
            v-if="deviceTreeStore.currentNodeKey&&currentNodeType==='设备型号'"
            class="opBtn"
            size=""
            type="primary"
            @click="AddAction"
          >
            新增
          </BaseButton>
               <BaseButton class="opBtn" size="" type="primary" @click="showFillTips">
            填报提示
          </BaseButton>
        </div>

        <!-- 数据表格 -->
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :columns="allSchemas.tableColumns"
          :data="dataList"
          :loading="loading"
          @register="tableRegister"
          :pagination="{ total }"
        />
      <!-- </ContentWrap> -->
    </div>

    <!-- 新增/编辑/查看对话框 -->
    <Dialog width="65%" v-model="dialogVisible" :title="dialogTitle">
      <!-- 表单组件（新增/编辑时显示） -->
      <Write
        class="opWrite"
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :current-node-name="currentNodeName"
      />

      <!-- 详情组件（查看时显示） -->
      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <!-- 对话框底部按钮 -->
      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          保存
        </BaseButton>
        <BaseButton @click="dialogVisible = false">关闭</BaseButton>
      </template>
    </Dialog>
       <Dialog
      v-model="fillTipsVisible"
      title="进口材料填报要求"
      width="700px"

    >
      <div class="fill-tips-content">
        <div class="tips-section">

          <div class="tips-item">
            <div v-html="fillTipsData"></div>
          </div>
        </div>
      </div>

      <template #footer>
        <BaseButton type="primary" @click="fillTipsVisible = false">确定</BaseButton>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="tsx">
import { ref, unref, reactive, watch, computed, onMounted, ComponentRef, nextTick } from "vue";
import { ContentWrap } from "@/components/ContentWrap";
import { Table } from "@/components/Table";
import { ElMessage, ElMessageBox } from "element-plus";
import { useTable } from "@/hooks/web/useTable";
import { Search } from "@/components/Search";
import Write from "./components/importedMaterialsWrite.vue";
import { useValidator } from "@/hooks/web/useValidator";
import Detail from "./components/importedMaterialsDetail.vue";
import { Dialog } from "@/components/Dialog";
import { CrudSchema, useCrudSchemas } from "@/hooks/web/useCrudSchemas";
import { BaseButton } from "@/components/Button";
import { useDictionaryStore } from "@/store/modules/dictionaryStore";
import { useDeviceTreeStore } from "@/store/modules/deviceTreeStore";
import { Edit, View, Delete } from "@element-plus/icons-vue";
import { directAxios } from "@/axios/index";
import { debounce } from 'lodash-es'
import { FORM_TYPES } from "@/utils/tips";


// ============ 初始化Store和工具函数 ============
const { required } = useValidator(); // 表单验证工具
const deviceTreeStore = useDeviceTreeStore(); // 设备树store
const dictionaryStore = useDictionaryStore(); // 字典store
// ============ 新增：填报提示相关数据 ============
// ============ 填报提示相关数据 ============
const fillTipsVisible = ref(false); // 填报提示弹框显示状态
const fillTipsData = ref(""); // 填报提示内容
const fillTipsLoading = ref(false); // 加载状态

/**
 * 加载填报提示数据
 */
const loadFillTipsData = async (): Promise<string> => {
  try {
    fillTipsLoading.value = true;
    const BASE_URL = import.meta.env.VITE_APP_BASE_URL || '/'
      const response = await fetch(`${BASE_URL}tips.json`);
    console.log(response,7890);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data[FORM_TYPES.IMPORTED_MATERIALS] || "暂无填报提示信息";
  } catch (error) {
    console.error('加载填报提示数据失败:', error);
    return "加载填报提示信息失败，请稍后重试";
  } finally {
    fillTipsLoading.value = false;
  }
}

/**
 * 显示填报提示弹框
 */
const showFillTips = async () => {
  try {
    fillTipsVisible.value = true;
    // 每次显示都重新加载，确保获取最新数据
    fillTipsData.value = await loadFillTipsData();
  } catch (error) {
    console.error('显示填报提示失败:', error);
    fillTipsData.value = "加载填报提示信息失败，请稍后重试";
  }
};
// ============ 响应式数据定义 ============

// 当前节点相关
const currentNodeType = ref(""); // 当前节点类型
const currentNodeName = ref(""); // 当前节点名称
const currentNodeKey = ref(deviceTreeStore.currentNodeKey); // 当前节点key
const currentNodeKeys = ref(); // 当前节点keys

// 防抖和加载控制
const loadingLock = ref(false)
const lastRequestKey = ref('') // 记录最后一次请求的key
let currentRequestId = 0 // 请求ID追踪

// 表格相关状态 - 使用useTable hook管理表格状态
const { tableRegister, tableState, tableMethods } = useTable({
  /**
   * 获取进口材料表格数据的API
   */
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState;
    const deviceCode = deviceTreeStore.currentNodeKey;

    // 如果没有选中设备节点，返回空数据
    if (!deviceCode) {
      return {
        list: [],
        total: 0,
      };
    }

    const res = await "/cImportedMaterials/page".get({
      deviceCode: deviceCode,
      missionCode: deviceTreeStore.taskInfo?.missionCode,
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
    });
    return {
      list: res.data.records || [],
      total: res.data.total || 0,
    };
  },
  immediate: false, // 禁用立即执行
});

// 解构表格状态和方法
const { total, loading, dataList, pageSize, currentPage } = tableState;
const { getList } = tableMethods;

// 搜索参数
const searchParams = ref({
  classificationCode: "",
});

// 对话框相关状态
const dialogVisible = ref(false); // 对话框显示状态
const dialogTitle = ref(""); // 对话框标题
const currentRow = ref(); // 当前操作的行数据
const actionType = ref(""); // 操作类型：'' | 'edit' | 'detail'
const saveLoading = ref(false); // 保存加载状态

// 组件引用
const writeRef = ref<ComponentRef<typeof Write>>(); // 表单组件引用

// ============ 计算属性 ============

// 类别选项
const classificationOptions = computed(() => {
  return dictionaryStore.dictionaries.get(
    dictionaryStore.DICTIONARY_TYPES.MA_CLASSIFICATION
  ) || [];
});

// 必要性等级选项
const necessityOptions = computed(() => {
  return dictionaryStore.dictionaries.get(
    dictionaryStore.DICTIONARY_TYPES.NECESSITY_LEVEL
  ) || [];
});

// 解决途径计划选项
const solutionPlanOptions = computed(() => {
  return dictionaryStore.dictionaries.get(
    dictionaryStore.DICTIONARY_TYPES.SOLUTION_PLAN
  ) || [];
});
// 对外依存度选项
const dependencyOptions = computed(() => {
  return dictionaryStore.dictionaries.get(
    dictionaryStore.DICTIONARY_TYPES.EXTERNAL_DEPENDENCE
  ) || [];
});
// 材料品种  MATERIAL_VARIETY
const materialVarietyOptions = computed(() => {
  return dictionaryStore.dictionaries.get(dictionaryStore.DICTIONARY_TYPES.MATERIAL_VARIETY) || [];
});
// ============ 防抖和安全获取方法 ============

/**
 * 防抖的获取列表方法
 */
const getListDebounced = debounce(async () => {
  if (loadingLock.value || loading.value) return

  const currentKey = deviceTreeStore.currentNodeKey
  if (!currentKey || !deviceTreeStore.currentTask) {
    dataList.value = []
    total.value = 0
    return
  }

  // 如果和上次请求的key相同，且数据已存在，则不重复请求
  const requestSignature = `${currentKey}-${deviceTreeStore.currentTask}`
  if (lastRequestKey.value === requestSignature && dataList.value.length > 0) {
    return
  }

  loadingLock.value = true
  lastRequestKey.value = requestSignature

  try {
    await getList()
  } finally {
    loadingLock.value = false
  }
}, 300)

/**
 * 安全获取方法
 */
const getListSafe = async () => {
  if (loadingLock.value) {
    return
  }

  if (!deviceTreeStore.currentNodeKey || !deviceTreeStore.currentTask) {
    dataList.value = []
    total.value = 0
    return
  }

  getList()
}

// ============ 监听器 ============

/**
 * 监听任务变化，当任务切换时刷新数据
 */
watch(
  () => deviceTreeStore.currentTask,
  async (newTask, oldTask) => {
    if (newTask && newTask !== oldTask) {
      currentPage.value = 1; // 重置分页
      dataList.value = []; // 清空旧数据
      searchParams.value = { classificationCode: "" } // 重置搜索条件

      // 使用nextTick确保在下一个事件循环执行
      await nextTick()

      // 生成新的请求ID
      const requestId = ++currentRequestId

      // 使用setTimeout确保在浏览器空闲时执行
      setTimeout(() => {
        // 检查是否仍然是最新的请求
        if (requestId === currentRequestId) {
          getListSafe()
        }
      }, 0)
    }
  }
);

/**
 * 监听设备树节点变化，刷新表格数据 - 主监听器
 */
watch(
  () => deviceTreeStore.currentNodeKey,
  async (newKey, oldKey) => {
    const node = deviceTreeStore.currentTreeNode
    currentNodeKey.value = newKey
    currentNodeKeys.value = newKey
    currentNodeName.value = node?.deviceName || ""
    currentNodeType.value = node?.nodeType || "" // 设置当前节点类型



    // 只有当节点真正变化时才刷新数据
    if (newKey && newKey !== oldKey) {
      currentPage.value = 1
      dataList.value = [] // 清空旧数据
      searchParams.value = { classificationCode: "" } // 重置搜索条件

      // 使用nextTick确保在下一个事件循环执行
      await nextTick()

      // 生成新的请求ID
      const requestId = ++currentRequestId

      // 使用setTimeout确保在浏览器空闲时执行
      setTimeout(() => {
        // 检查是否仍然是最新的请求
        if (requestId === currentRequestId) {
          getListSafe()
        }
      }, 0)
    }
  },
  { immediate: true, flush: 'post' } // 使用post确保在DOM更新后执行
);

// ============ 方法定义 ============

/**
 * 设置搜索参数并刷新表格
 * @param params 搜索参数
 */
const setSearchParams = (params: any) => {


  currentPage.value = 1;

  // 处理分类搜索 - 获取选中的文字
  if (params.category && params.category.length > 0) {
    const selectedTexts = getCascaderTexts(
      params.category,
      classificationOptions.value
    );

    searchParams.value = {
      ...params,
      classificationCode: params.category[params.category.length - 1] || "",
      // 添加文字搜索条件
      classificationText: selectedTexts.join(' , ') // 将文字路径保存
    };
  } else {
    searchParams.value = {
      ...params,
      classificationCode: "",
      classificationText: ""
    };
  }

  getList();
};
/**
 * 根据值和选项获取级联选择器的文字路径
 * @param values 选中的值数组
 * @param options 选项数组
 * @returns 文字路径数组
 */
const getCascaderTexts = (values: string[], options: any[]): string[] => {
  const texts: string[] = [];
  let currentOptions = options;

  for (const value of values) {
    const found = currentOptions.find(item => item.code === value);
    if (found) {
      texts.push(found.text);
      currentOptions = found.children || [];
    } else {
      break;
    }
  }

  return texts;
};
/**
 * 获取级联选择器的完整文字路径
 * @param values 选中的值数组
 * @param options 选项数组
 * @returns 完整的文字路径字符串
 */
const getFullCascaderText = (values: string[], options: any[]): string => {
  const texts = getCascaderTexts(values, options);
  return texts.join(' > ');
};

/**
 * 新增操作
 */
const AddAction = () => {
  if (currentNodeType.value !== "设备型号") {
    ElMessage.error("仅设备节点可新增");
    return;
  }
  dialogTitle.value = "新增";
  currentRow.value = {
    account: currentNodeName.value, // 设置所属设备名称
  };
  dialogVisible.value = true;
  actionType.value = "";
};

/**
 * 删除数据
 * @param row 要删除的行数据
 */
const delData = async (row?: any) => {
  ElMessageBox.confirm("是否确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const params = {
        id: row?.id,
      };
      const res = await directAxios.post(
        "/cImportedMaterials/delete",
        params,
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          transformRequest: [(data) => data.toString()],
        }
      );

      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      }
    })
    .catch(() => {});
};

/**
 * 行操作处理（编辑/查看）
 * @param row 行数据
 * @param type 操作类型：'edit' | 'detail'
 */
const action = (row: any, type: string) => {
  dialogTitle.value = type === "edit" ? "编辑" : "查看";
  actionType.value = type;

 // 构建级联选择器数据
  const categoryData = buildCategoryData(row);
const actualDeviceName = deviceTreeStore.getDeviceNameByCode(row.deviceCode);

  currentRow.value = {
    ...row,
    category: categoryData,
    account: actualDeviceName,
    classificationCode:categoryData[categoryData.length - 1] || "",
  };
  dialogVisible.value = true;
};

/**
 * 保存表单数据
 */
const save = async () => {
  const write = unref(writeRef);
  const formData = await write?.submit();

  if (formData) {
    saveLoading.value = true;
    try {
      const res = await "/cImportedMaterials/save".post({
        ...formData,
        deviceCode: currentNodeKeys.value, // 设置设备编码
        category: "", // 清空category字段
        classification1: currentRow.value.classification1 || "",
        classification2: currentRow.value.classification2 || "",
        classification3: currentRow.value.classification3 || "",
         missionCode: deviceTreeStore.taskInfo?.missionCode,
      });

      if (res) {
        currentPage.value = 1;
        getList();
        dialogVisible.value = false;
        ElMessage.success("保存成功");
      }
    } catch (error) {
      console.log("保存失败:", error);
    } finally {
      saveLoading.value = false;
    }
  }
};

/**
 * 处理类别选择变化
 * @param value 选中的值数组
 */
const handleCategoryChange = (value) => {
  const selectedOptions = getCascaderObj(
    value,
    dictionaryStore.dictionaries.get(dictionaryStore.DICTIONARY_TYPES.MA_CLASSIFICATION)
  );

  if (!currentRow.value) {
    currentRow.value = {};
  }

  // 清空之前的分类数据
  currentRow.value.classification1 = "";
  currentRow.value.classification2 = "";
  currentRow.value.classification3 = "";
  currentRow.value.classificationCode = "";
  currentRow.value.category = value;
  currentRow.value.classificationCode = selectedOptions[selectedOptions.length - 1].code;

  // 根据选中的层级设置对应的分类字段
  if (selectedOptions.length > 0) {
    currentRow.value.classification1 = selectedOptions[0]?.text || "";
  }
  if (selectedOptions.length > 1) {
    currentRow.value.classification2 = selectedOptions[1]?.text || "";
  }
  if (selectedOptions.length > 2) {
    currentRow.value.classification3 = selectedOptions[2]?.text || "";
  }
};

/**
 * 工具函数：根据值和选项获取级联选择器对象
 * @param val 选中的值数组
 * @param opt 选项数组
 * @returns 选中的选项对象数组
 */
const getCascaderObj = (val, opt) => {
  return val.map(function (value, index, array) {
    for (var itm of opt) {
      if (itm.code == value) {
        opt = itm.children;
        return itm;
      }
    }
    return null;
  });
};
/**
 * 根据分类名称查找对应的分类代码
 * @param names 分类名称数组 [一级名称, 二级名称, 三级名称]
 * @returns 分类代码数组
 */
const findCategoryCodesByName = (names: string[]): string[] => {
  const { DICTIONARY_TYPES } = dictionaryStore;
  const categoryOptions = dictionaryStore.dictionaries.get(DICTIONARY_TYPES.COM_CLASSFICATION) || [];

  const result: string[] = [];
  let currentLevel = categoryOptions;

  for (let i = 0; i < names.length; i++) {
    const name = names[i];
    if (!name) break;

    const found = currentLevel.find(item => item.text === name);
    if (found) {
      result.push(found.code);
      currentLevel = found.children || [];
    } else {
      // 如果没有找到匹配项，停止查找
      break;
    }
  }

  return result;
};

/**
 * 根据行数据构建级联选择器数据
 * @param row 行数据
 * @returns 级联选择器数据数组
 */
const buildCategoryData = (row: any): string[] => {
  // 如果已经有分类代码，直接返回处理过的数据
  if (row.classificationCode) {
    return row.classificationCode.length == 8
      ? [
          row.classificationCode.slice(0, 4),
          row.classificationCode.slice(0, 6),
          row.classificationCode,
        ]
      : row.classificationCode.length == 6
        ? [
            row.classificationCode.slice(0, 4),
            row.classificationCode.slice(0, 6),
          ]
        : [row.classificationCode.slice(0, 4)];
  }

  // 如果没有分类代码，根据分类名称查找
  const names = [
    row.classification1,
    row.classification2,
    row.classification3
  ].filter(Boolean); // 过滤掉空值

  if (names.length > 0) {
    return findCategoryCodesByName(names);
  }

  return [];
};
// ============ CRUD表结构配置 ============

/**
 * 进口材料管理表结构配置
 */
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: "selection",
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: "selection", hidden: true },
  },
  {
    field: "index",
    label: "序号",
    form: { hidden: true },
    search: { hidden: true },
    detail: { hidden: true },
    table: { type: "index" },
  },
  {
    field: "account",
    label: "所属设备",
    width: 90,
    search: { hidden: true },
    form: {
      component: "Input",
      value: currentNodeName.value,
      componentProps: {
        placeholder: "请输入所属设备",
        disabled: true,
      },
    },
    table: { hidden: true },
  },
  {
    field: "classificationCode",
    label: "分类代码",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 100,
    form: {
      hidden: true,

      componentProps: {
        placeholder: "请输入分类代码",
        disabled: true,
      },
      formItemProps: { rules: [required()] },
    },
    detail: { hidden: true, },
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: { placeholder: "分类代码" },
    },
    table: { hidden: true },
  },
  {
    field: "category",
    label: "类别",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 250,
    search: {
      component: "Cascader",
      componentProps: {
        placeholder: "类别",
        options: classificationOptions,
        props: {
          checkStrictly: false,
          emitPath: true,
          label: "text",
          value: "code",
        },
         onChange: (value: any[]) => {
        // 这里可以实时获取选中的文字
        if (value && value.length > 0) {
          const selectedTexts = getCascaderTexts(value, classificationOptions.value);
          console.log('选中的文字:', selectedTexts);
          console.log('完整路径:', selectedTexts.join(' > '));
        }
      },
      },
    },
    form: {
      component: "Cascader",
      formItemProps: {
        rules: [{ required: true, message: "请选择类别" }],
      },
      componentProps: {
        placeholder: "请选择类别",
        options: classificationOptions,
        props: {
          checkStrictly: false,
          emitPath: true,
          label: "text",
          value: "code",
        },
        onChange: (value: any[]) => {
          handleCategoryChange(value);
        },
      },
    },
    detail: { hidden: true },
    table: {
         formatter: (row: any) => {
        // 组合分类字段，用 > 分隔，空值用 / 代替
        const parts = [
          row.classification1 || "/",
          row.classification2 || "/",
          row.classification3 || "/",
        ];
         return parts.join(" > ");
      },
    },
  },
  {
    field: "classification1",
    label: "一级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "classification2",
    label: "二级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "classification3",
    label: "三级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "materialName",
    label: "材料名称",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 120,
    form: {
      formItemProps: {
        rules: [
          { required: true, message: "请输入材料名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入材料名称" },
        ],
      },
      componentProps: { placeholder: "请输入材料名称" },
    },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "材料名称" },
    },
  },
  {
    field: "materialGrade",
    label: "材料牌号",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "材料牌号" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入材料牌号" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入材料牌号" },
        ],
      },
      componentProps: { placeholder: "请输入材料牌号" },
    },
  },
  {
    field: "materialVariety",
    label: "材料品种",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 150,
    search: {
      component: "Select",
      label: "",
      hidden: false,
      componentProps: { placeholder: "材料品种",
         options: materialVarietyOptions,
       },
    },
    form: {
     component: "Select",

      formItemProps: {
        rules: [
          { required: true, message: "请输入材料品种" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入材料品种" },
        ],
      },
      componentProps: {
        placeholder: "请选择材料品种",
        options:materialVarietyOptions
      },
    },
  },
  {
    field: "materialSupplyStatus",
    label: "材料供应状态",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 120,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "材料供应状态" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入材料供应状态" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入材料供应状态" },
        ],
      },
      componentProps: { placeholder: "请输入材料供应状态" },
    },
  },
  {
    field: "materialSpecification",
    label: "材料规格",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "材料规格" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入材料规格" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入材料规格" },
        ],
      },
      componentProps: { placeholder: "请输入材料规格" },
    },
  },
  {
    field: "materialStandardNo",
    label: "材料标准号",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: { placeholder: "材料标准号" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入材料标准号" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入材料标准号" },
        ],
      },
      componentProps: { placeholder: "请输入材料标准号" },
    },
  },
  {
    field: "materialStandardName",
    label: "材料标准名称",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 150,
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "材料标准名称" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入材料标准名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入材料标准名称" },
        ],
      },
      componentProps: { placeholder: "请输入材料标准名称" },
    },
  },
  {
    field: "quantityPerDevice",
    label: "单个设备使用材料数量（kg）",
    width: 240,
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    sortable: true,
    search: {
      hidden: false,
      componentProps: { placeholder: "单个设备使用材料数量（kg）" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入单个设备使用材料数量" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入单个设备使用材料数量",
        min: 0,
      },
    },
  },
  {
    field: "referencePrice",
    label: "参考价格(元)",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入参考价格" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入参考价格",
        min: 0,
        precision: 2,
      },
    },
  },
  //  {
  //   field: "isPre",
  //   label: "是否优选",
  //   width: 90,
  //   form: {
  //     hidden: true
  //   },
  //   search: { hidden: true },
  // },
  {
    field: "manufacturer",
    label: "生产厂商",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 120,
    search: { hidden: true },
    detail: { span: 12 },
    form: {
      component: "Input",
      colProps: { span: 12 },
      formItemProps: {
        rules: [
          { required: true, message: "请输入生产厂商" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入生产厂商" },
        ],
      },
      componentProps: { placeholder: "请输入生产厂商" },
    },
  },
    {
    field: "externalDependence",
    label: "对外依存度",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 80,
    search: {
      component: "Select",
      label: "",
      hidden: true,
      componentProps: {
        placeholder: "对外依存度",
        options: dependencyOptions,
      },
    },
    table: { hidden: true },
    form: {
      component: "Select",
      formItemProps: {
        rules: [{ required: true, message: "请选择对外依存度" }],
      },
      componentProps: {
        placeholder: "请输入对外依存度",
        options: dependencyOptions,
      },
    },
  },
  //
    {
    field: "riskAnalysis",
    label: "风险分析",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 90,
    search: {
      component: "Input",
      label: "风险分析",
      hidden: true,
      componentProps: { placeholder: "风险分析" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入风险分析" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入风险分析" },
        ],
      },
      componentProps: { placeholder: "请输入风险分析" },
    },
  },

  {
    field: "necessityLevel",
    label: "选用必要性",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Select",
      value: "",
      componentProps: {
        placeholder: "请选择必要性",
        options: necessityOptions,
      },
      formItemProps: {
        rules: [{ required: true, message: "请选择必要性" }],
      },
    },
  },
  {
    field: "solutionApproach",
    label: "后续解决方案",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 120,
    search: {
      component: "Input",
      label: "",
      hidden: true,
      componentProps: { placeholder: "解决途径" },
    },
    detail: { span: 12 },
    form: {
      component: "Select",
      colProps: { span: 12 },
      formItemProps: {
        rules: [{ required: true, message: "请选择解决途径" }],
      },
      componentProps: {
        placeholder: "请输入解决途径",
        options: solutionPlanOptions,
      },
    },
  },
  {
    field: "personInCharge",
    label: "负责人",
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入负责人" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入负责人" },
        ],
      },
      componentProps: { placeholder: "请输入负责人" },
    },
  },
  {
    field: "contactInfo",
    label: "联系方式",
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      componentProps: { placeholder: "请输入联系方式" },
      formItemProps: {
        rules: [
          { required: true, message: "请输入联系方式" },
          { pattern: /^[0-9]{11}$/, message: "请输入正确的联系方式" },
        ],
      },
      colProps: { span: 12 },
    },
  },
  {
    field: "remarks",
    label: "备注",
    width: 90,
        showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.IMPORTED_MATERIALS,
    },
    search: { hidden: true },
    detail: { span: 24 },
    form: {
      component: "Input",
      componentProps: {
        type: "textarea",
        rows: 3,
        placeholder: "请输入备注信息",
      },
      colProps: { span: 24 },
    },
    table: { hidden: true },
  },
  {
    field: "action",
    label: "操作",
    fixed: "right",
    form: { hidden: true },
    detail: { hidden: true },
    search: { hidden: true },
    table: {
      width: 170,
      fixed: "right",
      slots: {
        default: (data: any) => {
          const row = data.row;
          return (
            <>
              <div style="display:flex;color: var(--el-color-primary)">
                <div class="flex-1 cursor-pointer" onClick={() => action(row, "edit")}>
                  <el-icon>
                    <Edit />
                  </el-icon>
                  编辑
                </div>
                <div class="flex-1 cursor-pointer" onClick={() => action(row, "detail")}>
                  <el-icon>
                    <View />
                  </el-icon>
                  查看
                </div>
                <div class="flex-1 cursor-pointer" onClick={() => delData(row)}>
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </div>
              </div>
            </>
          );
        },
      },
    },
  },
]);

// 使用CRUD Schemas hook
// const { allSchemas } = useCrudSchemas(crudSchemas);
const { allSchemas } = useCrudSchemas(crudSchemas, {
  showTips: true, // 这里必须设置为 true
  defaultFormType: FORM_TYPES.IMPORTED_MATERIALS,
});

// ============ 生命周期 ============

/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  // 预加载常用字典
  await dictionaryStore.preloadCommonDictionaries();

  // 设置当前节点名称
  currentNodeName.value = deviceTreeStore.currentTreeNode?.deviceName || "";
  // 设置当前节点类型
  currentNodeType.value = deviceTreeStore.currentTreeNode?.nodeType || "";

  // 注意：不要在mounted中调用getList，让watch的immediate处理
});

defineExpose({
  getList: getListSafe // 暴露安全版本
});
</script>

<style scoped lang="less">
:deep(.el-divider--horizontal) {
  margin: 5px 0 15px 0;
}

.mb-10px {
  display: flex;
}
:deep(.el-card__body ){
  padding: 20px  0 !important;
}
</style>
